package dbtek;

import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author Mikko Puustinen (mikko.puustinen@gmail.com)
 * @version 0.1, 2008-mar-17
 */
public class OrderView {
    private boolean isRunning;
    private Scanner scanner;
    private OrderController controller;

    /**
     *
     */
    public OrderView(OrderController controller) {
        //TODO
        this.controller = controller;
        isRunning = true;
        scanner = new Scanner(System.in);
    }

    /**
     *
     */
    public void program() {
        char choice;
        do {
            System.out.println("////////////////////////////////////");
            if (controller.isSignedOn()) {
                System.out.println("\nSigned in as: " + controller.getUsername());
            }
            System.out.print("1. Sign in\n2. Search\n3. Add book to cart\n4. Show cart\n5. Finish order\nQ. Quit session\n> ");
            choice = scanner.nextLine().charAt(0);

            switch (choice) {
                case '1':
                    signIn();
                    break;
                case '2':
                    searchBook();
                    break;
                case '3':
                    addBookToCart();
                    break;
                case '4':
                    showCart();
                    break;
                case '5':
                    finishOrder();
                    break;
                case 'q':
                case 'Q':
                    endSession();
                    return;
                default:
                    //
            }

        } while (isRunning);
    }

    private void endSession() {
        char res;

        System.out.print("Are you sure you want to end the session(y/n)\n\t(Note: All unsaved changes will go lost)\n > ");
        if ((res = scanner.nextLine().charAt(0)) == 'Y' || res == 'y') {
            try {
                controller.endSession();
            } catch (SQLException e) {
                System.err.println("Error when finishing session: " + e.getMessage());
                return;
            }

            System.out.println("\n\nSession data deleted. You are now signed off.");
        }
    }

    /**
     *
     */
    private void finishOrder() {
        if (!controller.isOrderStarted()) {
            System.err.println("No order in progress");
            return;
        }

        String time;
        char res;

        showCart();

        System.out.print("\nDo you want to finish this order? (y/n)\n > ");

        if ((res = scanner.nextLine().charAt(0)) == 'y' || res == 'Y') {
            try {
                time = controller.finishOrder();
            } catch (SQLException e) {
                System.err.println("Error when finishing order: " + e.getMessage());
                return;
            } catch (Exception e) {
                System.err.println(e.getMessage());
                return;
            }

            System.out.println("\n\nOrder finished at " + time);
        }
    }

    /**
     *
     */
    private void showCart() {
        String res;
        String[] cart;
        int i;

        try {
            res = controller.showCart();
        } catch (SQLException e) {
            System.err.println("Error when fetching cart: " + e.getMessage());
            return;
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
            return;
        }

        cart = res.split("\n");

        System.out.println("Items in cart:\n-----");
        for (i = 0; i < cart.length - 1; i++) {
            System.out.println(i + 1 + ".) " + cart[i]);
        }

        System.out.println("-----\nSum: " + cart[i] + "\n-----");
    }

    /**
     *
     */
    private void addBookToCart() {
        if (!controller.isSignedOn()) {
            System.err.println("You must sign in before adding books.");
            return;
        }

        String isbn;
        int qty;

        System.out.print("\n\nAdd item to cart\nISBN > ");
        isbn = scanner.nextLine();
        System.out.print("Quantity > ");
        String res = scanner.nextLine();
        try {
            qty = Integer.parseInt(res);
        } catch (NumberFormatException e) {
            qty = 1;
        }

        if (qty < 0) {
            qty = 1;
        }

        try {
            controller.addBookToCart(isbn, qty);
        } catch (SQLException e) {
            System.err.println("Error when adding item: " + e.getMessage());
            return;
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
            return;
        }

        System.out.println("\n\nAdded " + qty + " items of " + isbn);
    }

    /**
     *
     */
    private void searchBook() {
        String res;
        String[] books;
        Object[] b;

        System.out.print("\n\nSearch (ISBN, Title, Publisher, Author) [Wildcard: %]\n\t > ");
        res = scanner.nextLine();
        try {
            b = controller.searchBook(res);
        } catch (SQLException e) {
            System.err.println("Error when searching for book: " + e.getMessage());
            return;
        }

        int r = b.length;

        System.out.println("\n\nFetched " + r + " result(s):\n-------");
        if (r < 1) {
            System.out.println("\tNo results for " + res);
        } else {
            for (Object o : b) {
                books = o.toString().split("::");

                System.out.println("ISBN:  " + books[0]);
                System.out.println("Title: " + books[1] + " (Edition " + books[2] + ")");
                System.out.println("Price: " + books[3]);

                if (Integer.parseInt(books[4]) > 0) {
                    System.out.println("\tIn Stock");
                } else {
                    System.out.println("\tOut of stock");
                }
                System.out.println("-----");
            }
        }

        System.out.println("");
    }

    /**
     *
     */
    private void signIn() {
        String username;
        String password;

        System.out.print("\n\nSign in\n\tUsername > ");
        username = scanner.nextLine();
        System.out.print("\tPassword > ");
        password = scanner.nextLine();
        try {
            controller.signIn(username, password);
        } catch (SQLException e) {
            System.err.println("Could not sign in: " + e.getMessage());
            return;
        }

        if (!controller.isSignedOn()) {
            System.err.println("Could not sign in.");
        }
    }
}
